﻿using System;
using ARPGCommon;
using ARPGCommon.Model;
using ARPGPhotonServer.DB.Manager;
using ARPGPhotonServer.Tools;
using LitJson;
using Photon.SocketServer;

namespace ARPGPhotonServer.Handlers
{
    internal class LoginHandler : HandlerBase
    {
        public static string Host = "http://gameproxy.xinmei365.com/game_agent/checkLogin";

        private readonly UserManager _manager;

        public LoginHandler()
        {
            _manager = new UserManager();
        }

        public override OperationResponse OnHandlerMeesage(OperationRequest request, ClientPeer peer)
        {
            //判断数据类型
            var subCode = ParameterTool.GetParameter<SubCode>(request.Parameters, ParameterCode.SubCode, false);
            var response = new OperationResponse {OperationCode = request.OperationCode};

            switch (subCode)
            {
                case SubCode.CheckUserInfoBySelfData:
                    //1.获得客户端发送的帐号和明文密码
                    var user = ParameterTool.GetParameter<User>(request.Parameters, ParameterCode.UserCheckInfo);
                    var userDb = _manager.GetUserByUsername(user.Username);

                    //2.比较,然后创建响应
                    if (userDb != null && userDb.Password == MD5Tool.GetMD5(user.Password))
                    {
                        response.ReturnCode = (short) ReturnCode.Success;
                        peer.SetUser(userDb);
                    }
                    else
                    {
                        response.ReturnCode = (short) ReturnCode.Fail;
                        response.DebugMessage = "用户名或密码错误!";
                    }
                    break;
                case SubCode.CheckUserInfoByChannelData:
                    //从SDK服务器处验证渠道用户信息接口
                    var data = ParameterTool.GetParameter<string>(request.Parameters, ParameterCode.UserCheckInfo);
                    var jsonData = JsonMapper.ToObject(data);

                    //确认渠道登录成功
                    if (VerifyChannelUserIsLogin(jsonData))
                    {
                        //查找user信息
                        var userId = jsonData["userId"].ToString();
                        var channel = jsonData["channel"].ToString();

                        userDb = _manager.GetUserByUserSDkId(userId);

                        if (userDb == null)
                        {
                            //不存在,新建
                            userDb = new User()
                            {
                                Username = channel + ":" + userId,
                                Password = userId,
                                UserSDkId = userId
                            };
                            _manager.RegisterUser(userDb);
                        }

                        //登录成功
                        response.ReturnCode = (short) ReturnCode.Success;
                        peer.SetUser(userDb);
                    }
                    else
                    {
                        response.ReturnCode = (short) ReturnCode.Fail;
                        response.DebugMessage = "登录失败!";
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            return response;
        }

        /// <summary>
        /// 向SDK服务器确定渠道用户
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private bool VerifyChannelUserIsLogin(JsonData jsonData)
        {
            return Http.Url(Host)
                .parameter("productCode", jsonData["productCode"].ToString()) //产品标识
                .parameter("channel", jsonData["channel"].ToString()) //渠道标识
                .parameter("userId", jsonData["userId"].ToString()) //用户id，这个用户id不是渠道的用户id,这个是我方处理后的不会重复的用户id。
                .parameter("token", jsonData["token"].ToString()) //token 令牌
                .IsLoginIn();
        }


        protected override OperationCode OpCode
        {
            get { return OperationCode.Login; }
        }
    }
}